﻿using Autofac;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.FileProviders;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using ZingBlog.Web.Filters;
using ZingFrameworkCore.Common.Cache;
using ZingFrameworkCore.Common.Injection;

namespace ZingBlog.Web
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {

            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", true, true)
                .Build();
            services.AddSingleton<IConfiguration>(configuration);

            services.AddMvc();
            services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
            services.AddControllers().AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
                options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
                options.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverter());
                options.JsonSerializerOptions.PropertyNamingPolicy = null;
            });

            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(120);
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
            });
            services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "DataProtection"));
            services.AddControllersWithViews().AddRazorRuntimeCompilation();
            services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();
            services.Configure<MvcOptions>(option =>{
                option.Filters.Add<GlobalAuthorizeFilter>();
            });
            ServiceProviderAccessor.SetServiceProvider(services);
        }
        public void ConfigureContainer(ContainerBuilder containerBuilder)
        {
            containerBuilder.RegisterModule<AutofacDefaultModule>();
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles().UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider($"{AppContext.BaseDirectory}\\Content"),
                RequestPath = "/Content"
            }).UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider($"{AppContext.BaseDirectory}\\ErrorPage"),
                RequestPath = "/ErrorPage"
            }).UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider($"{AppContext.BaseDirectory}\\Upload"),
                RequestPath = "/Upload"
            }); ;

            app.UseSession();

            var httpcontextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
            app.UseHttpContext(httpcontextAccessor);
            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
                endpoints.MapAreaControllerRoute(name: "AdminArea", areaName: "Admin", pattern: "Admin/{controller=Home}/{action=Index}/{id?}");
                endpoints.MapAreaControllerRoute(name: "PermissionsArea", areaName: "Permissions", pattern: "Permissions/{controller=Home}/{action=Index}/{id?}");
                endpoints.MapAreaControllerRoute(name: "BlogArea", areaName: "Blog", pattern: "Blog/{controller=Home}/{action=Index}/{id?}");
                endpoints.MapAreaControllerRoute(name: "SysSetArea", areaName: "SysSet", pattern: "SysSet/{controller=Home}/{action=Index}/{id?}");
            });
             
        }
    }
}
